/**
 * 屏幕宽度改变触发回调
 */

import React from 'react';
import { IPAD_WIDTH } from '@/config/define';

interface ViewportProps {
  children: React.ReactNode;
}

interface ViewportValue {
  width: number;
  height: number;
}

export const viewportContext = React.createContext<ViewportValue>({
  width: 0,
  height: 0,
});

// 包裹在React根节点，确保能够在其子组件访问到
export const ViewportProvider = (props: ViewportProps) => {
  const [width, setWidth] = React.useState(window.innerWidth);
  const [height, setHeight] = React.useState(window.innerHeight);

  const handleWindowResize = () => {
    setWidth(window.innerWidth);
    setHeight(window.innerHeight);
  };

  React.useEffect(() => {
    window.addEventListener('resize', handleWindowResize);
    return () => window.removeEventListener('resize', handleWindowResize);
  }, []);

  return (
    <viewportContext.Provider value={{ width, height }}>
      {props.children}
    </viewportContext.Provider>
  );
};

/**
 *
 const MyComponent = () => {
  const { width } = useViewport();
  const breakpoint = 620;

  return width < breakpoint ? <MobileComponent /> : <DesktopComponent />;
}
 */

export type WindowType = 'phone' | 'pc';

// 在React的子组件中，提供快捷访问的入口
export const useViewport = () => {
  const { width, height } = React.useContext(viewportContext);
  let type: WindowType = 'pc';
  if (width < IPAD_WIDTH) {
    type = 'phone';
  } else if (width > IPAD_WIDTH) {
    type = 'pc';
  }
  return { width, height, type };
};
